package com.zx.cloud.common.token;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 3DES加密工具类
 */
public class Des3 {

	public static void main(String[] args) throws Exception {
		String usenId = "23";
		String userIdEncode = Des3.encode(usenId);
		System.out.println("userIdEncode[" + userIdEncode + "]");
		String toJid = userIdEncode + "@804039.ichengyun.net";
		String toUser_ = toJid.split("[@]")[0];
		System.out.println("toUser_[" + toUser_ + "]");
		String toUserId_ = Des3.decode(toUser_);
		System.out.println("toUser_[" + toUser_ + "],toUserId_[" + toUserId_ + "]");
	}

	// 密钥
	private final static String secretKey = "magic_appfff098tghhlx100ergeg365ergeg";
	// 向量
	private final static String iv = "01234567";
	// 加解密统一使用的编码方式
	private final static String encoding = "utf-8";

	public static String encode(String plainText) throws Exception {
		Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
		cipher.init(Cipher.ENCRYPT_MODE, createKey(), ips);
		byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
		return Encodes.encodeBase64(encryptData);
	}

	public static Key createKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {// 创建密钥
		DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
		Key deskey = keyfactory.generateSecret(spec);
		return deskey;
	}

	public static String decode(String encryptText) throws Exception {
		Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
		cipher.init(Cipher.DECRYPT_MODE, createKey(), ips);
		byte[] decryptData = cipher.doFinal(Encodes.decodeBase64(encryptText));
		return new String(decryptData, encoding);
	}
}